package com.dkd.system.controller;

import com.dkd.common.core.domain.AjaxResult;
import com.dkd.system.domain.TWarranty;
import com.dkd.system.mapper.TWarrantyMapper;
import com.dkd.system.utils.QRCodeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/qrcode")
@Slf4j
public class QRCodeController {

    @Autowired
    private TWarrantyMapper tWarrantyMapper;

    @GetMapping("/{id}")
    public AjaxResult generateQRCode(@PathVariable("id") String id) {
        log.info("查询的二维码ID及密钥是{}",id);
        if ("".equals(id) || id == null) {
            return AjaxResult.error("暂无参数，不能访问！");
        }
        TWarranty tWarranty = new TWarranty();
        if (id.contains("-")) {
            //如何包含- 相当于已加密的连接 包含的话根据-拆分 第一位是id 后面是密钥
            //查询数据库 相同返回 不相同直接return
            String[] strs = id.split("-");
            String selectId = strs[0]; //id
            String secret = strs[1]; //密钥
            TWarranty warranty = tWarrantyMapper.selectTWarrantyById(Integer.valueOf(selectId));
            String warrantySecret = warranty.getSecret();
            if (!"".equals(secret) && !"".equals(warrantySecret)) {
                if (secret.equals(warrantySecret)) {
                    tWarranty = warranty;
                } else {
                    return AjaxResult.error("密钥错误，不能访问！");
                }
            }
        } else {
            //如果不包含- 相当于9.1日未加密的连接
            //根据id查询数据的加密列，如果未空，那么就是直接返回数据
            TWarranty warranty = tWarrantyMapper.selectTWarrantyById(Integer.valueOf(id));
            String secret = warranty.getSecret();
            if (secret == null || "".equals(secret)) {
                tWarranty = warranty; //赋值对象
            } else {
                return AjaxResult.error("密钥错误，不能访问！");
            }
        }
        tWarranty.setJsonData(null);
        tWarranty.setQrcodeLocation(null);
        return AjaxResult.success(tWarranty);
    }

    @PostMapping("/qrcode/gen")
    public ResponseEntity<byte[]> generateQRCode(
            @RequestParam String url,
            @RequestParam String type,
            @RequestParam(required = false) MultipartFile logo,
            @RequestParam(required = false) MultipartFile bgImg) throws IOException {

        if (url == null || url.isEmpty()) {
            return ResponseEntity.badRequest().body("URL cannot be empty".getBytes());
        }

        try {
            byte[] qrCodeBytes;
            switch (type) {
                case "black":
                    qrCodeBytes = QRCodeGenerator.generateBlackAndWhiteQRCode(url);
                    break;
                case "logo":
                    if (logo == null || logo.isEmpty()) {
                        return ResponseEntity.badRequest().body("请上传Logo文件".getBytes());
                    }
                    qrCodeBytes = QRCodeGenerator.generateQRCodeWithLogo(url, logo.getInputStream());
                    break;
                case "color":
                    qrCodeBytes = QRCodeGenerator.generateColorQRCode(url);
                    break;
                case "background":
                    if (bgImg == null || bgImg.isEmpty()) {
                        return ResponseEntity.badRequest().body("请上传背景图".getBytes());
                    }
                    qrCodeBytes = QRCodeGenerator.generateBackgroundImageQRCode(url, bgImg.getInputStream());
                    break;
                case "shape":
                    qrCodeBytes = QRCodeGenerator.generateSpecialShapeQRCode(url);
                    break;
                case "imageFill":
                    if (logo == null || logo.isEmpty()) {
                        return ResponseEntity.badRequest().body("请上传填充图片".getBytes());
                    }
                    qrCodeBytes = QRCodeGenerator.generateImageFilledQRCode(url, logo.getInputStream());
                    break;
                case "gif":
                    if (bgImg == null || bgImg.isEmpty()) {
                        return ResponseEntity.badRequest().body("请上传GIF背景图".getBytes());
                    }
                    qrCodeBytes = QRCodeGenerator.generateGifQRCode(url, bgImg.getInputStream());
                    break;
                default:
                    return ResponseEntity.badRequest().body("Invalid QR code type".getBytes());
            }
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_PNG) // 或 MediaType.IMAGE_GIF
                    .body(qrCodeBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body("生成二维码失败".getBytes());
        }
    }
}


